package thread;

/**
 * @author DBX
 * @effect
 * @date 2021/09/01/20:41
 */
public class ThreadTest2 {
    private static Account act;
    public static void main(String[] args) {
        act = new Account();
        Thread t = new Thread(){
            @Override
            public void run() {
                act.withdraw(5000);
            }
        };
        Thread t1 = new Thread(){
            @Override
            public void run() {
                act.withdraw(5000);
            }
        };
        t.start();
        t1.start();
    }
}

class Account{
//    账户
    private String actno;
//    余额
    private double balance = 10000;

    public String getActno() {
        return actno;
    }

    public void setActno(String actno) {
        this.actno = actno;
    }

    public double getBalance() {
        return balance;
    }

    public void setBalance(double balance) {
        this.balance = balance;
    }

    public Account(String actno, double balance) {
        this.actno = actno;
        this.balance = balance;
    }

    public Account() {
    }
    public void withdraw(double money) {

        synchronized (this) {
            double before = this.getBalance();
            if (before >= money) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(before);
                setBalance(before - money);
            }
            System.out.println(Thread.currentThread().getName() + "取了" + money + ",还剩：" + getBalance());
        }
    }
}